import Vue from 'vue'

const cart = {
	namespaced: true,
	state: () => ({
		// 购物车
		shop_cart: {
			'':[],
			'陈烨': [],//[{id: ,img: ,price: ,num: ,title: , },]
			'黄承智':[],
			'钟易辰':[],
		},
		paylist: [],
		totalnumber:0, //商品总数量
	}),
	getters: {
		
	},
	mutations: {
		// 退出重置购物车数量
		recount_num(state){
			state.totalnumber = 0
		},
		// 向用户购物车添加商品
		add_shop(state, shop) {
			state.shop_cart[shop.username].push({
				id: shop.id,
				img: shop.img,
				title: shop.title,
				num: shop.num,
				price: shop.price
			})
			state.totalnumber += 1;
			// 同步持久化存储购物车
			localStorage.setItem(shop.username,JSON.stringify(state.shop_cart[shop.username]))
		},
		//shop为对象，包含当前用户及删除书的id
		del_shop(state,shop) {
			Vue.prototype.$messagebox.confirm('您确定要删除该宝贝吗?')
			.then(() => {
				var cartlist = state.shop_cart[shop.username]
				for (var i=0;i<cartlist.length;i++){
					if (cartlist[i].id == shop.id){
						cartlist.splice(i,1)
					}
				}
				state.totalnumber -=1
				localStorage.setItem(shop.username,JSON.stringify(state.shop_cart[shop.username]))
			})
			.catch(() => {
				
			})
		},
		// shop :用户名、商品id、是否增加
		// shop:{
		// 	username: '',
		// 	id: '',
		// 	isincrease: true or false
		// }
		modifynum(state,shop) {
			var cartlist = state.shop_cart[shop.username]
			for (var i=0;i<cartlist.length;i++){
				if (cartlist[i].id == shop.id){
					shop.isincrease?cartlist[i].num += 1:cartlist[i].num -= 1
				}
			}
		},
		// 登录时用户时添加用户的购物车
		add_user(state,user) {
			// 如果本地存储到有这个用户的购物车，使用本地的数据
			if(localStorage.getItem(user.username)){
				Vue.set(state.shop_cart, user.username, JSON.parse(localStorage.getItem(user.username)));
				// 同步购物车内商品数量数据
				state.totalnumber = state.shop_cart[user.username].length;
			}
			// 如果没有就建立新的购物车
			else{
				Vue.set(state.shop_cart, user.username, [])
			}
			
		},
		// 准备付款的商品id列表
		before_pay(state, ids) {
			state.paylist = ids
		},
		// 付款
		pay(state, user) {
			let new_cart = [];
			for (let item of state.shop_cart[user.username]){
				state.paylist.indexOf(item.id) == -1 ? new_cart.push(item) : {};
			}
			state.shop_cart[user.username] = new_cart;
			localStorage.setItem(user.username,JSON.stringify(state.shop_cart[user.username]))
			state.totalnumber -= state.paylist.length 
			state.paylist = []
		},
		// 结算买单
		settleacc(state) {
		}
	},
	actions: {
		
	}
}

export default cart;